package com.gking.aiService.utils.commonUtil;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 自定义验证码类
 */
public class VerifyImageUtil {
    private int width = 100;    //生成验证码图片的宽度
    private int height = 40;    //生成验证码图片的高度
    private final String[] fontNames = {"微软雅黑"}; // "宋体", "楷体", "隶书", "微软雅黑"
    private final Color bgColor = new Color(255, 255, 255); //定义验证码图片的背景色
    private final Random random = new Random();
    private final String verifyCode;    //记录随机字符串

    public VerifyImageUtil(String verifyCode) {
        this.verifyCode = verifyCode;
    }

    public VerifyImageUtil(String verifyCode, int width, int height) {
        if (height < 40) height = 40;
        if (width < 100) width = 100;
        this.verifyCode = verifyCode;
        this.width = width;
        this.height = height;
    }

    /**
     * 获取随机一个颜色
     *
     * @return s
     */
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 获取随机一个字体
     *
     * @return s
     */
    private Font randomFont() {
        String name = fontNames[random.nextInt(fontNames.length)];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(name, style, size);
    }

    /**
     * 创建一个空白的BufferedImage对象
     *
     * @return s
     */
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(bgColor);
        g2.fillRect(0, 0, width, height);
        return image;
    }

    /**
     * 绘制干扰线
     */
    private void drawLine(BufferedImage image) {
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        int num = 2;
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2.setColor(randomColor());
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 绘制验证码
     *
     * @return s
     */
    public BufferedImage getImage() {
        BufferedImage image = createImage();
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        String[] codeArr = this.verifyCode.split("");
        for (int i = 0; i < codeArr.length; i++) {
            String s = codeArr[i];
            g2.setColor(randomColor());
            g2.setFont(randomFont());
            float x = i * width * 1.0f / 4;
            g2.drawString(s, x, height - 15);
        }
        drawLine(image);
        return image;
    }


}
